<?php
/**
 * This is the base Digitalus Model and adds a number of convenience methods to Zend_Db_Table
 */
abstract class Dig_Model_Abstract extends Zend_Db_Table_Abstract 
{
    /**
     * this method adds some convenience to saving data
     * 
     * it determines whether to insert or update
     * depending on whether the id is set
     *
     * @param mixed $data
     *
     * @return mixed
     */
    public function save($data)
    {
        foreach ($data as $key => $value) {
            if(! $cleanData[$key] = $this->_callSetterMethod($key, $data)) {
                $cleanData[$key] = $value;
            }
        }
        if(isset($cleanData['id'])) {
            $id = $cleanData['id'];
            unset($cleanData['id']);
            return $this->update($cleanData, $this->_db->quoteInto('id = ?', $id));
        } else {
            return $this->insert($cleanData);
        }
    }

    /**
     * This method enables you to save a form directly to a model
     *
     * Behind the scenes it validates that each field in the form exists in the underlying table
     * 
     * @param Zend_Form $form
     * 
     * @return boolean
     */
    public function saveForm(Zend_Form $form)
    {
        $cleanData = array();
        $cols = $this->info('cols'); 
        $formData = $form->getValues();
        foreach ($cols as $col) {
            if(array_key_exists($col, $formData)) {
                $cleanData[$col] = $formData[$col];
            }
        }
        return $this->save($cleanData);
    }

    /**
     * This is a convenience method which enables you to delete an item by its primary key
     *
     * @param integer $id the primary key of the row to delete
     */
    public function deleteById($id)
    {
        $row = $this->find($id)->current();
        if($row) {
            $row->delete();
        }
    }

    /**
     * This is a magic method which enables you to add setters to your model classes.
     *
     * The save method uses this method internally, which enables you to provide
     * callback methods in your models.
     * 
     * @param string $property
     * @param array $data
     * 
     * @return mixed
     */
    protected function _callSetterMethod ($property, $data)
    {
        //create the method name
        $method = Zend_Filter::filterStatic($property, 'Word_UnderscoreToCamelCase');
        $methodName = '_set' . $method;
        if (method_exists($this, $methodName)) {
            return $this->$methodName($data);
        }
        return false;
    }
}
?>